package com.sinochem.iot.rule.service;

import com.sinochem.iot.rule.mapper.RuleActionMapper;
import com.sinochem.iot.rule.mapper.RuleConditionMapper;
import com.sinochem.iot.rule.mapper.TriggerMapper;
import com.sinochem.iot.rule.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;


@Service
public class TriggerService {
    @Autowired
    private TriggerMapper triggerMapper;
    @Autowired
    private TriggerRuleService triggerRuleService;
    @Autowired
    private TriggerRuleStoreService triggerRuleStoreService;
    @Autowired
    private TriggerRuleDetailService triggerRuleDetailService;

    @Autowired
    private RuleConditionMapper ruleConditionMapper;
    @Autowired
    private RuleActionMapper ruleActionMapper;

    /**
     * 分页查询触发器
     *
     * @param example
     * @return
     */
    public List<Trigger> selectByExample(TriggerExample example) {
        return triggerMapper.selectByExample(example);
    }

    /**
     * 创建触发器
     *
     * @param record
     * @return
     */
    public int insert(Trigger record) {
        return triggerMapper.insertSelective(record);
    }

    /**
     * 触发器详情
     *
     * @param id
     * @return
     */
    public Trigger selectByPrimaryKey(Integer id) {
        return triggerMapper.selectByPrimaryKey(id);
    }

    /**
     * 删除触发器
     *
     * @param id
     * @return
     */
    public int deleteByPrimaryKey(Integer id) {
        return triggerMapper.deleteByPrimaryKey(id);
    }

    /**
     * 修改触发器
     *
     * @param record
     * @return
     */
    public int updateByPrimaryKeySelective(Trigger record) {

        record.setUpdateTime(new Date());
        return triggerMapper.updateByPrimaryKeySelective(record);
    }

    /**
     * 事务删除触发器
     * @param id
     * @return
     */
    @Transactional
    public int delTriggerById(Integer id){
        TriggerRule triggerRule = triggerRuleService.getTriggerRuleByTriId(id);
        if (triggerRule != null) {
            Integer ruleId = triggerRule.getId();
            ruleConditionMapper.deleteByRuleId(ruleId);
            ruleActionMapper.deleteByRuleId(ruleId);
            triggerRuleService.delTriggerRule(ruleId);
            triggerRuleDetailService.deleteByRuleId(ruleId);
        }
        return deleteByPrimaryKey(id);
    }

    /**
     * 事务修改触发器状态
     * @param trigger
     */
    @Transactional
    public void updTriggerStatus(Trigger trigger,TriggerRule triggerRule){
        updateByPrimaryKeySelective(trigger);
        //同时修改t_trigger_rule_detail表里的状态
        TriggerRuleDetail triggerRuleDetail = new TriggerRuleDetail();

        triggerRuleDetail.setRuleId(triggerRule.getId());
        triggerRuleDetail.setStatus(trigger.getStatus());
        triggerRuleDetailService.updateStatusByRuleId(triggerRuleDetail);
    }

}
